//
//  CYAddressBookTVController.m
//  CreditAddressBook
//
//  Created by Lee on 15/4/20.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYAddressBookTVController.h"
#import <AddressBook/AddressBook.h>
#import "CYCommon.h"
#import "AddressBook.h"
#import "PinYin4Objc.h"

@interface CYAddressBookTVController ()

@property (nonatomic, strong) NSMutableArray *allPeople;
@property (nonatomic, strong) NSMutableArray *peopleSections;
@property (nonatomic, strong) NSMutableArray *pinYinHead;
@property (nonatomic, strong) NSMutableArray *chineseSort;
@end

@implementation CYAddressBookTVController

- (NSMutableArray *)allPeople {
    if (_allPeople == nil) {
        _allPeople = [NSMutableArray array];
    }
    return _allPeople;
}

- (NSMutableArray *)peopleSections {
    if (_peopleSections == nil) {
        _peopleSections = [NSMutableArray array];
    }
    return _peopleSections;
}

- (NSMutableArray *)pinYinHead {
    if (_pinYinHead == nil) {
        _pinYinHead = [NSMutableArray array];
    }
    return _pinYinHead;
}

- (NSMutableArray *)chineseSort {
    if (_chineseSort == nil) {
        _chineseSort = [NSMutableArray array];
    }
    return _chineseSort;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestAccessAddressBook];

}

/**
 *  读取通讯录授权
 */
- (void)requestAccessAddressBook {
    ABAddressBookRef book = ABAddressBookCreateWithOptions(NULL, NULL);
    ABAddressBookRequestAccessWithCompletion(book, ^(bool granted, CFErrorRef error) {
        if (granted) {
            CYLog(@"授权成功");
            [self accessAllPeople];
            [self toPinYinHead];
            [self.tableView reloadData];
        }else {
//            CYLog(@"授权失败");
        }
    });
    
    CFRelease(book);
}

- (void)accessAllPeople {
//    if (ABAddressBookGetAuthorizationStatus() != kABAuthorizationStatusAuthorized) return;
//    
//    ABAddressBookRef book = ABAddressBookCreateWithOptions(NULL, NULL);
//    NSArray *peoples = (__bridge NSArray *)ABAddressBookCopyArrayOfAllPeople(book);
//    
//    for (int i = 0; i < peoples.count; i++) {
//        ABRecordRef record = (__bridge ABRecordRef)peoples[i];
//        //获取用户姓名
//        NSString *firstName = (__bridge NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty);
//        NSString *lastName = (__bridge NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty);
//        CYLog(@"name:%@ %@ \n", lastName, firstName);
//        //获取用户电话数组
//        ABMultiValueRef phone = ABRecordCopyValue(record, kABPersonPhoneProperty);
//        // 获得更详细的数据类型
//        NSArray *phoneArray = (__bridge NSArray *)(ABMultiValueCopyArrayOfAllValues(phone));
//        for (int j = 0; j < phoneArray.count; j++) {
//            NSString *phoneLabel = (__bridge NSString *)(ABMultiValueCopyLabelAtIndex(phone, j));
//            NSString *phoneValue = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(phone, j));
//            NSLog(@"%@ - %@", phoneLabel, phoneValue);
//        }
//        CFRelease(phone);
//    }
//    
//    CFRelease(book);
    
    RHAddressBook *book = [[RHAddressBook alloc] init];
    NSArray *peoples = [book people];
//    NSArray *groups = [book groups];
//    for (RHGroup *group in groups) {
//        CYLog(@"%@", group.name);
//    }
    
    [self.allPeople addObjectsFromArray:peoples];
    
}

- (void)toPinYinHead {
    //1获取姓名的数组
    NSMutableArray *names = [NSMutableArray array];
    for (RHPerson *person in self.allPeople) {
        [names addObject:person.name];
    }
    //2获取首字母并排序
    NSArray *pinyinHead = [PinYinForObjc pinYinHead:names];
    [self.pinYinHead addObjectsFromArray:pinyinHead];
    CYLog(@"%@", pinyinHead);
    //3汉字排序, 返回二维数组
    NSArray *chineseScort = [PinYinForObjc chineseSort:names];
    //4对RHPersonsp排序
    NSArray *personSort = [self.allPeople sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        RHPerson *p1 = obj1;
        RHPerson *p2 = obj2;
        NSString *p1name = [[PinYinForObjc chineseConvertToPinYin:p1.name] uppercaseString];
        NSString *p2name = [[PinYinForObjc chineseConvertToPinYin:p2.name] uppercaseString];
        return [p1name compare:p2name];
    }];
    CYLog(@"self.allPeople排序%@", personSort);
    //5根据汉字分组排序对RHPersons进行分组排序
    NSMutableArray *personSections = [NSMutableArray array];
    int indexOfArr = 0;//personSort数组的下标
    for (int i = 0; i < chineseScort.count; i++) {
        NSMutableArray *persons = [NSMutableArray array];
        NSArray *chinese = chineseScort[i];
        for (int j = indexOfArr; j < chinese.count + indexOfArr; j++) {
            [persons addObject:personSort[j]];
        }
        indexOfArr += chinese.count;//personSort数组的下标
        [personSections addObject:persons];
    }
    [self.chineseSort addObjectsFromArray:personSections];
    CYLog(@"分组后的person：%@", self.chineseSort);
}

-(void)viewDidAppear:(BOOL)animated {
    if (ABAddressBookGetAuthorizationStatus() != kABAuthorizationStatusAuthorized) {
         
        [[[UIAlertView alloc] initWithTitle:nil message:CYFailureCue delegate:nil cancelButtonTitle:CYToolTips otherButtonTitles:nil] show];
         
    }
    [super viewDidAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.pinYinHead.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *sections = self.chineseSort[section];
    return sections.count;
    
    
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.pinYinHead[section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    NSArray *persons = self.chineseSort[indexPath.section];
    RHPerson *person = persons[indexPath.row];
    cell.textLabel.text = person.name;
//    RHMultiValue *phones = person.phoneNumbers;
//    NSUInteger count = persons.count;
//    for (int i = 0; i < count; i++) {
//        NSString *phone = phones.values[i];
//    }
    cell.detailTextLabel.text = person.phoneNumbers.values[1];
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

@end
